<template>
  <el-upload
    ref="upload"
    v-bind="{
      beforeUpload: beforeUpload,
      beforeRemove: beforeRemove,
      onExceed: handleExceed,
      onChange: handleChange,
      onRemove: handleChange,
      ...$attrs,
      ...$props,
    }"
  >
    <slot>
      <el-button type="primary">上传附件</el-button>
    </slot>
    <span v-if="hitInline" slot="tip"> {{ hit }} </span>
    <div v-else slot="tip">{{ hit }}</div>
  </el-upload>
</template>

<script>
export default {
  name: "Upload",
  model: {
    prop: "value",
    event: "change",
  },
  props: {
    limit: {
      type: Number,
      default: 1,
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    autoUpload: {
      type: Boolean,
      default: false,
    },
    action: {
      type: String,
      default: "",
    },
    accept: {
      type: String,
      default: ".jpg,.png",
    },
    hit: {
      type: String,
      default: "只能上传jpg/png文件，且不超过10M",
    },
    hitInline: {
      type: Boolean,
      default: true,
    },
    maxSize: {
      type: Number,
      default: 10 * 1024 * 1024, // 10MB
    },
  },
  methods: {
    beforeUpload(file) {
      if (file.size > this.maxSize) {
        this.$message.warning("上传文件不能大于10M");
        return false;
      }
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.limit} 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    handleChange(file, fileList) {
      const attaches = fileList.map((c) => c.raw);
      this.$emit("change", attaches);
      const showFileList =
        this.$attrs.showFileList || this.$attrs["show-file-list"];
      if (showFileList === false) {
        this.$refs.upload.clearFiles();
      }
    },
  },
};
</script>

<style lang="less" scoped></style>
